﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using AtletIS.Shared.Entities;
using AtletIS.Shared.Helpers;
using AtletIS.Shared.Events;

namespace AtletIS.Shared.Forms
{
    public partial class frmTrack : Form
    {
        #region Private fields

        private DisciplineListEntity _discipline;
        private FalseStartHelper _falseStartHelper;

        #endregion

        #region Ctor

        public frmTrack(DisciplineListEntity discipline)
        {
            InitializeComponent();

            this._discipline = discipline;
            this.Icon = Properties.Resources.Track64;
        }

        #endregion

        #region Event handlers

        // Form Load
        private void frmTrack_Load(object sender, EventArgs e)
        {
            this.taResultCodes.Fill(this.aDbDataSet.ResultCodes);
            this.Text = string.Format("TRACK :: {0} ({1})", _discipline.Name, _discipline.ID);

            this.ReloadPerformances();

            // Nastavi port a ten zavola ConnectToFalseStart
            this.nudPort.Value = Globals.FalseStartPort.Value;
        }

        // Port changed
        private void nudPort_ValueChanged(object sender, EventArgs e)
        {
            Globals.FalseStartPort = (int)nudPort.Value;
            this.ConnectFalseStart();
        }

        // Ulozit
        private void tsbSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.Validate();
                this.bsPerformances.EndEdit();
                this.taPerformances.Update(this.aDbDataSet.Performances);

                // Update Status
                Helpers.StatusHelper.UpdateStatus(_discipline, Globals.StatusFinished);

                // Update performances
                ResultsHelper.UpdatePerformances(_discipline);

                Globals.ActiveDiscipline = _discipline;

                this.ReloadPerformances();
            }
            catch (Exception ex)
            {
                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        // Zmazat vsetky reakcie
        private void tsbClearReactions_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.aDbDataSet.Performances != null && this.aDbDataSet.Performances.Count > 0)
                {
                    foreach (DataRow item in this.aDbDataSet.Performances.Rows)
                    {
                        item["Reaction"] = string.Empty;
                    }

                    this.taPerformances.Update(this.aDbDataSet.Performances);
                }
            }
            catch (Exception ex)
            {
                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        // Koniec
        private void tsbClose_Click(object sender, EventArgs e)
        {
            _falseStartHelper.Dispose();
            this.Close();
        }

        #endregion

        #region Private methods

        private void ReloadPerformances()
        {
            DatabaseHelper.FillPerformancesByDisciplineListId(this.aDbDataSet.Performances, _discipline.ID);
            this.tsslCount.Text = string.Format("Počet pretekárov: {0}", this.aDbDataSet.Performances.Count);
        }

        private void ConnectFalseStart()
        {
            _falseStartHelper = new FalseStartHelper();

            if (_falseStartHelper != null && _falseStartHelper.IsConnected)
            {
                _falseStartHelper.DataProcessed += new EventHandler(falseStartHelper_DataProcessed);
                this.nudPort.BackColor = Color.GreenYellow;
            }
            else
                this.nudPort.BackColor = Color.Red;
        }

        private void falseStartHelper_DataProcessed(object sender, EventArgs e)
        {
            try
            {
                if (e != null && e is FalseStartEventArgs)
                {
                    var fsArgs = (FalseStartEventArgs)e;
                    var reactions = fsArgs.Reactions;

                    if (reactions != null && reactions.Count > 0)
                    {
                        foreach (var item in reactions)
                        {
                            string filter = string.Format("Lane = {0}", item.Key);

                            DataRow[] rows = this.aDbDataSet.Performances.Select(filter);
                            if (rows != null && rows.Length > 0)
                            {
                                rows[0]["Reaction"] = item.Value;
                            }
                        }

                        this.BeginInvoke(new EventHandler(UpdateDataFromFalseStart));
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        private void UpdateDataFromFalseStart(Object sender, EventArgs e)
        {
            this.taPerformances.Update(this.aDbDataSet.Performances);
            this.ReloadPerformances();   
        }

        #endregion

        


    }
}
